//
//  LSZComposeView.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/17.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
import pop

class LSZComposeView: UIView {
    
//    存储目标控制器
    private var target: UIViewController?
    
//    存储创建的composeButton
    private lazy var composeButtonArray = [LSZComposeMenuButton]()
    
    
    // MARK:懒加载控件
    
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    添加一个显示动画
    func show(target: UIViewController){
        
        self.target = target
        
        target.view.addSubview(self)
        
//        开启动画
        for (i , value) in composeButtonArray.enumerate() {
            startAnimation(value, i: i, isUp: true)
        }
        
    }
    
    
//    添加控件设置约束
    func setUpUI() {
        backgroundColor = RandomColor()
        
//        设置视图大小
        self.frame.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        
//        添加控件
        addSubview(bgImageView)
        
//        设置约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        
        addChildButton()
    }

    
//    读取plist文件
    private func loadComposePlist() -> [LSZComposeMenu] {
        
//        获取路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
    
//        读取plist文件
        let composeDicArray = NSArray(contentsOfFile: path!)!
        
    
        var tempArray = [LSZComposeMenu]()
        
        for dic in composeDicArray {
            let composeMenu = LSZComposeMenu(dic: dic as! [String : AnyObject])
            tempArray.append(composeMenu)
        }
        return tempArray
    }
    
//    添加6个子控件
    private func addChildButton() {
        
//        按钮的宽度
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
//        按钮的间距
        let itemMargin: CGFloat = (width - 3 * buttonWidth) / 4
//        获取plist文件的数据
        let composeMenuArray = loadComposePlist()
        
        for (i , value) in composeMenuArray.enumerate() {
            
            let button = LSZComposeMenuButton()
//            设置模型
            button.composeMenu = value
//            添加点击事件
            button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
//            计算列的索引
            let col = i % 3
//            计算行的索引
            let row = i / 3
            
//            计算x 的坐标
            button.x = buttonWidth * CGFloat(col) + CGFloat(col + 1) * itemMargin
            
            button.y = buttonHeight * CGFloat(row) + CGFloat(row) * itemMargin + ScreenHeight
            
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            
            button.setTitle(value.title, forState: .Normal)
            
            addSubview(button)
            
//            添加到指定数组
            composeButtonArray.append(button)
        }
        
    }
    
    // MARK: 按钮的点击事件
    @objc private func buttonAction(btn: LSZComposeMenuButton) {
        
       UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.composeButtonArray {
                //                设置alpha
                value.alpha = 0.2
                if value == btn {
                    //                    被点击的这个就要放大
                    value.transform = CGAffineTransformMakeScale(1.2, 1.2)
                } else {
                    //                    其他的按钮缩小
                    value.transform = CGAffineTransformMakeScale(0.8, 0.8)
                }
            }
        }) { (_) -> Void in
            
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
//               动画结束后让按钮的状态还原
                for value in self.composeButtonArray {
                    value.alpha = 1
                    value.transform = CGAffineTransformIdentity
                }
   
            }, completion: { (_) -> Void in
                
              let classType = NSClassFromString(btn.composeMenu!.className!) as! UIViewController.Type
                
                
//                创建指定的对象
                let vc = classType.init()
                
//                创建导航控制器
                let nav = UINavigationController(rootViewController: vc)
                
                
                self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
                
            })
            
            
        }
    }
    
    
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
     
//        关闭动画
        for (i , value) in composeButtonArray.reverse().enumerate() {
            startAnimation(value, i: i, isUp: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
//            结束刷新
            self.removeFromSuperview()
        })
        
     
    }

}

extension LSZComposeView  {
//    开启pop动画
    private func startAnimation(value: UIButton, i: Int, isUp: Bool) {
        
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
   
//        动画执行的目的地
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        
        
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
 //        设置弹簧效果抖动幅度访问 range [0, 20]
        animation.springBounciness = 8
//        抖动的初始速度
        animation.springSpeed = 10
//        开始的动画时间,表示一次执行的时间间隔
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
//        执行动画
        value.pop_addAnimation(animation, forKey: nil)
        
    }
}